<script lang="ts" setup>
import type { RowType } from '../../types';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { $t } from '@vben/locales';
import { useVbenModal } from '@vben/common-ui';
const baseUrl = import.meta.env.VITE_GLOB_API_URL
import {
  Button,
  Image,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteSlideItems,
  getSlideItems,
  postSlideItemsListOrder,
  postSlideItemsToggle,
} from '#/api/admin/slideItems';
import Icon from '#/components/Icons';
import { formatImagesList, sortByField, toggleStatus } from '#/utils';

import DataFormModalView from './DataFormModal.vue';

const slideId = ref();
const [TableModal, modalApi] = useVbenModal();
const gridOptions: VxeGridProps<RowType> = {
  rowConfig: {
    useKey: true,
    drag: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { field: 'id', title: $t('page.common.Code'), width: 50, dragSort: true },
    { field: 'title', title: $t('page.common.Title') },
    { field: 'description', title: $t('page.common.Description') },
    { field: 'url', title: $t('admin.linkAddress') , slots: { default: 'url' }},
    { field: 'target', title: $t('admin.Open Method') },
    { field: 'image', title: $t('page.common.Image'), slots: { default: 'image' } },
    
    { field: 'status', title: $t('page.common.Status'), slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const modalData = modalApi.getData();
        slideId.value = modalData.id;
        const { data } = await getSlideItems({ slide_id: modalData.id });

        const list = sortByField(data.list, 'list_order');
        data.list = formatImagesList(list);
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const gridEvents: VxeGridListeners<RowType> = {
  async rowDragend() {
    const visibleData = await GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });
    await postSlideItemsListOrder({ list_orders: result });
  },
};

const handleDelete = async (row: RowType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteSlideItems(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const [DataFormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: DataFormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const openDialog = async (title: 'Add' | 'Edit', row?: null | RowType) => {
  formModalApi.setState({
    title: $t('page.common.'+title)+` `+$t('page.menu.Data'),
  });
  const data = row || { slide_id: slideId.value };

  formModalApi.setData(data);
  formModalApi.open();
};

const onChange = async (row: RowType) => {
  Modal.confirm({
    title: $t('admin.systemMessage'),
    content: $t('admin.confirmTo')+` ${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}?`,
    async onOk() {
      try {
        await postSlideItemsToggle(row.id);
        message.success(`${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};
</script>
<template>
  <TableModal :footer="false" class="w-3/5">
    <DataFormModal />

    <Grid :grid-events="gridEvents" :table-title="$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('Add')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}}
        </Button>
      </template>
      <template #url="{ row }">
           <a :href="`${baseUrl}${row.url}`" target="_blank"  v-if="row.url">{{baseUrl}}{{row.url}}</a>
      </template>
      <template #image="{ row }">
        <Image v-if="row.image" :src="row.image[0]['url']" height="20" width="20" />
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :un-checked-value="0"
          :checked-children="$t('admin.Enable')"
          :un-checked-children="$t('admin.Disable')"
          @change="onChange(row)"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('Edit', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t('page.common.Edit')}}
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
               {{$t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </TableModal>
</template>
